#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define SEC_PER_HOUR 3600
#define SEC_PER_MIN 60

int fileListStart;
int speed;

int readArguments(int, char**);
char* printTime(time_t);

int main(int argc, char* argv[])
{
	int fileNumber;
	time_t prgm_start_time = time(NULL);
	time_t loop_start_time, elapsed_time;
	unsigned long long fileSize, i;
	char c[1];
	FILE* pFile;
	c[0] = (char) 0x00;
	fileListStart = 1;
	speed = 1;

	readArguments(argc,argv);

	if (argc > fileListStart) for (fileNumber = fileListStart ; fileNumber < argc ; fileNumber++)
	{
		pFile = fopen (argv[fileNumber],"r+");
		if (pFile != NULL)
		{
			loop_start_time = time(NULL); // Begin timer
			
			printf("Deleting %30.30s\t% 5.2f%%", argv[fileNumber], 0.0);
			// Calculate size of file
			fseek(pFile,0,SEEK_END);
			fileSize = ftell(pFile);
			fseek(pFile,0,SEEK_SET);

			// Overwrite each byte with 0x00
			if (fileSize > 0) for (i = 0 ; i < fileSize ; i += speed)
			{
				printf("\rDeleting %30.30s\t% 5.2f%%", argv[fileNumber], (i*100.0)/(fileSize-1));
				fseek(pFile, speed-1, SEEK_CUR);
				fwrite(c,sizeof(c[0]),sizeof(c)/sizeof(c[0]),pFile); // Overwrites the file
			}
			// If file is empty, nothing will be overwritten, and the user should be informed
			else printf(" File %s is empty", argv[fileNumber]); 
			fclose(pFile);

			// Delete file
			if (remove(argv[fileNumber]) == -1)
				printf(" Error deleting file: %s", argv[fileNumber]); // Inform the user if an error has occurred
			printf(" (%ld seconds)\n", time(NULL) - loop_start_time);
		}
		else printf("Could not open file: %s\n", argv[fileNumber]); // Inform user that an error has occurred
	}
	else printf("No files specified\n");

	// Exit program
	elapsed_time = time(NULL) - prgm_start_time;
	printf("Tasks completed in ");
	printTime(elapsed_time);
	printf("\n");
	return 0;
}

int readArguments(int argc, char* argv[])
{
	int i;
	for (i = 1 ; i < argc ; i++)
	{
		
		if (argv[i][0] == '-')
		{
			if (argv[i][1] == 'h' || strcmp(argv[i],"--help"))	// help command
			{
				printf("Print the help manual\n");
				exit(EXIT_SUCCESS);
			}
			else if (argv[i][1] == 's' || strcmp(argv[i], "--speed") == 0) // Speed command
			{
				speed = atoi(argv[i+1]);
				fileListStart += 2;
			}
		}
	}
	return 0;
}

char* printTime(time_t totalTime)
{
	printf("%d hours %d minutes %d seconds", totalTime/SEC_PER_HOUR, (totalTime%SEC_PER_HOUR)/SEC_PER_MIN, totalTime%SEC_PER_MIN);
}
